#region File Description
//-----------------------------------------------------------------------------
// PauseMenuScreen.cs
//
// Microsoft XNA Community Game Platform
// Copyright (C) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
#endregion

#region Using Statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework.Net;
using Microsoft.Xna.Framework.Storage;
using Alone;
using Alone.GameObjects;
using AloneLibrary.Services.Camera;
using AloneLibrary.Services.Input;
using AloneLibrary.Services.Sound;
using AloneLibrary;
using AloneLibrary.GameObjects;
using Alone.GameObjects.Enemy;
using Alone.Handlers;
using System.Xml.Serialization;
using System.IO;
#endregion

namespace Alone.Screens
{
    /// <summary>
    /// The pause menu comes up over the top of the game,
    /// giving the player options to resume or quit.
    /// </summary>
    public class GameOverScreen : MenuScreen
    {

        [Serializable]
        public struct HighScoreData
        {
            public string[] PlayerName;
            public int[] Score;
           

            public int Count;

            public HighScoreData(int count)
            {
                PlayerName = new string[count];
                Score = new int[count];

                Count = count;
            }
        }

        #region Fields

        NetworkSession networkSession;
        Texture2D backgroundTexture;
        IPlayerHandler playerhandler;
        int score;
        public readonly string filename = "higscore.lst";

        SpriteFont font; 

        #endregion

        #region Initialization


        /// <summary>
        /// Constructor.
        /// </summary>
        public GameOverScreen(NetworkSession networkSession)
            : base(Resources.GameOver)
        {
            //backgroundTexture = ScreenManager.Game.Content.Load<Texture2D>("GameOverBackground");
            this.networkSession = networkSession;

            // Flag that there is no need for the game to transition
            // off when the pause menu is on top of it.
            //IsPopup = true;

            // Add the Resume Game menu entry.
            //MenuEntry resumeGameMenuEntry = new MenuEntry(Resources.ResumeGame);
            //resumeGameMenuEntry.Selected += OnCancel;
            //MenuEntries.Add(resumeGameMenuEntry);
           
            if (networkSession == null)
            {
                // If this is a single player game, add the Quit menu entry.
                MenuEntry quitGameMenuEntry = new MenuEntry(Resources.TryAgain);
                quitGameMenuEntry.Selected += QuitGameMenuEntrySelected;
                MenuEntries.Add(quitGameMenuEntry);
                //quitGameMenuEntry.Selected += OnCancel;
            }
            else
            {
                // If we are hosting a network game, add the Return to Lobby menu entry.
                if (networkSession.IsHost)
                {
                    MenuEntry lobbyMenuEntry = new MenuEntry(Resources.ReturnToLobby);
                    lobbyMenuEntry.Selected += ReturnToLobbyMenuEntrySelected;
                    MenuEntries.Add(lobbyMenuEntry);
                }

                // Add the End/Leave Session menu entry.
                string leaveEntryText = networkSession.IsHost ? Resources.EndSession :
                                                                Resources.LeaveSession;

                MenuEntry leaveSessionMenuEntry = new MenuEntry(leaveEntryText);
                leaveSessionMenuEntry.Selected += LeaveSessionMenuEntrySelected;
                MenuEntries.Add(leaveSessionMenuEntry);
            }
        }

        public override void LoadContent()
        {
            // Get the path of the save game
            string fullpath = Path.Combine(StorageContainer.TitleLocation, filename);

            // Check to see if the save exists
            if (!File.Exists(fullpath))
            {
                //If the file doesn't exist, make a fake one...
                // Create the data to save
                HighScoreData data = new HighScoreData(5);
                data.PlayerName[0] = "Micke";
                data.Score[0] = 20050;

                data.PlayerName[1] = "Danne";
                data.Score[1] = 9870;

                data.PlayerName[2] = "Jonte";
                data.Score[2] = 4133;

                data.PlayerName[3] = "Nicke";
                data.Score[3] = 951;

                data.PlayerName[4] = "Steffe";
                data.Score[4] = 100;

                SaveHighScores(data, filename);
            }

            playerhandler = (IPlayerHandler)ScreenManager.Game.Services.GetService(typeof(IPlayerHandler));
            score = playerhandler.Score;

            font = ScreenManager.Game.Content.Load<SpriteFont>("gamefont");

            SaveHighScore();
            base.LoadContent();
        }

        private void checkHighScore()
        {
            
        }


        #endregion

        #region Handle Input


        /// <summary>
        /// Event handler for when the Quit Game menu entry is selected.
        /// </summary>
        void QuitGameMenuEntrySelected(object sender, PlayerIndexEventArgs e)
        {
            ScreenManager.Game.Services.RemoveService(typeof(ISoundManager));
            ScreenManager.Game.Services.RemoveService(typeof(IPlayerHandler));
            ScreenManager.Game.Services.RemoveService(typeof(IEnemyHandler));
            ScreenManager.Game.Services.RemoveService(typeof(IBallisticsHandler));
            ScreenManager.Game.Services.RemoveService(typeof(IEnvironmentHandler));

            LoadingScreen.Load(ScreenManager, false, null, new BackgroundScreen(),
                                                           new MainMenuScreen());
            //MessageBoxScreen confirmQuitMessageBox =
            //                        new MessageBoxScreen(Resources.ConfirmQuitGame);

            //confirmQuitMessageBox.Accepted += ConfirmQuitMessageBoxAccepted;

            //ScreenManager.AddScreen(confirmQuitMessageBox, ControllingPlayer);
        }


        /// <summary>
        /// Event handler for when the user selects ok on the "are you sure
        /// you want to quit" message box. This uses the loading screen to
        /// transition from the game back to the main menu screen.
        /// </summary>
        void ConfirmQuitMessageBoxAccepted(object sender, PlayerIndexEventArgs e)
        {
            LoadingScreen.Load(ScreenManager, false, null, new BackgroundScreen(),
                                                           new MainMenuScreen());
        }


        /// <summary>
        /// Event handler for when the Return to Lobby menu entry is selected.
        /// </summary>
        void ReturnToLobbyMenuEntrySelected(object sender, PlayerIndexEventArgs e)
        {
            if (networkSession.SessionState == NetworkSessionState.Playing)
            {
                networkSession.EndGame();
            }
        }


        /// <summary>
        /// Event handler for when the End/Leave Session menu entry is selected.
        /// </summary>
        void LeaveSessionMenuEntrySelected(object sender, PlayerIndexEventArgs e)
        {
            NetworkSessionComponent.LeaveSession(ScreenManager, e.PlayerIndex);
        }

        /// <summary>
        /// When the user cancels the main menu, ask if they want to exit the sample.
        /// </summary>
        protected override void OnCancel(PlayerIndex playerIndex)
        {
            QuitGameMenuEntrySelected(null, null);
        }


        #endregion

        #region Draw


        /// <summary>
        /// Draws the pause menu screen. This darkens down the gameplay screen
        /// that is underneath us, and then chains to the base MenuScreen.Draw.
        /// </summary>
        public override void Draw(GameTime gameTime)
        {
            ScreenManager.FadeBackBufferToBlack(TransitionAlpha * 2 / 3);

            HighScoreData highScore = LoadHighScores(filename);
           
            SpriteBatch spriteBatch = ScreenManager.SpriteBatch;
            //Viewport viewport = ScreenManager.GraphicsDevice.Viewport;
            //Rectangle fullscreen = new Rectangle(0, 0, viewport.Width, viewport.Height);
            //byte fade = TransitionAlpha;

            spriteBatch.Begin(SpriteBlendMode.AlphaBlend);


            spriteBatch.DrawString(font,"High Score",new Vector2(430,200),Color.White);
            for (int i = 0; i < highScore.Count; i++)
            {
                spriteBatch.DrawString(font, highScore.PlayerName[i]+": "+highScore.Score[i], new Vector2(470, 270+(i*50)), Color.White,0,Vector2.Zero,0.5f,SpriteEffects.None,0);
            }

            spriteBatch.End();
            base.Draw(gameTime);
        }


        #endregion

        private void SaveHighScores(HighScoreData data, string filename)
        {
            // Get the path of the save game
            string fullpath = Path.Combine(StorageContainer.TitleLocation, filename); //NOTE: XNA 3.0 no longer allows writing to the TitleLocation.  To save data that is
            //not tied to a specific gamertag, use one of the Guide.BeginShowStorageDeviceSelector
            //overloads that does not specify a PlayerIndex.
            // Open the file, creating it if necessary
            FileStream stream = File.Open(fullpath, FileMode.OpenOrCreate);
            try
            {
                // Convert the object to XML data and put it in the stream
                XmlSerializer serializer = new XmlSerializer(typeof(HighScoreData));
                serializer.Serialize(stream, data);
            }
            finally
            {
                // Close the file
                stream.Close();
            }
        }
        private HighScoreData LoadHighScores(string filename)
        {
            HighScoreData data;

            // Get the path of the save game
            string fullpath = Path.Combine(StorageContainer.TitleLocation, filename);

            // Open the file
            FileStream stream = File.Open(fullpath, FileMode.OpenOrCreate,
            FileAccess.Read);
            try
            {

                
                // Read the data from the file
                XmlSerializer serializer = new XmlSerializer(typeof(HighScoreData));
                data = (HighScoreData)serializer.Deserialize(stream);
            }
            finally
            {
                // Close the file
                stream.Close();
            }

            return (data);
        }

        private void SaveHighScore()
        {
            // Create the data to save
            HighScoreData data = LoadHighScores(filename);

            int scoreIndex = -1;
            for (int i = 0; i < data.Count; i++)
            {
                if (score > data.Score[i])
                {
                    scoreIndex = i;
                    break;
                }
            }

            if (scoreIndex > -1)
            {
                //New high score found ... do swaps
                for (int i = data.Count - 1; i > scoreIndex; i--)
                {
                    data.PlayerName[i] = data.PlayerName[i - 1];
                    data.Score[i] = data.Score[i - 1];
                }
                data.PlayerName[scoreIndex] = "Local player";
                if (SignedInGamer.SignedInGamers.Count > 0)
                    data.PlayerName[scoreIndex] = SignedInGamer.SignedInGamers[0].Gamertag;
                data.Score[scoreIndex] = score;

                SaveHighScores(data, filename);
            }
        }
    }
}
